package linuxbox.filelib.servlet;

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

import linuxbox.filelib.logic.*;
import linuxbox.common.*;
import linuxbox.util.*;
import linuxbox.BoxStatic;

/**
 * <p>Title: Linuxbox</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author Xia,Xunfan
 * @version 1.0
 */

public class UploadFileAction extends Action
{
  protected static String folderContentJSP = null;

  protected static Logger logger = Logger.getLogger(UploadFileAction.class);
  protected static FileLibHome home = FileLibHome.getInstance();

  public void doAction(HttpSession session, BoxSession aBoxSession,
  HttpServletRequest req, HttpServletResponse resp) throws Exception
  {
    if (logger.isDebugEnabled())
      logger.debug("====== Start of UploadFileAction ======");
    FileLibEntry entry = (FileLibEntry) session.getAttribute("filelib.CURENTRY");
    if (entry == null)
    {
      String msg = "Can't find record! ";
      logger.error(msg);
      sendError(msg, req, resp);
      return;
    }
    boolean isNew = (entry.getID()==-1);
    if (isNew)
    {
      FileLibEntry newEntry = home.add();
      entry.setId(newEntry.getID());
      entry.setCreatetime(new Timestamp(System.currentTimeMillis()));
      entry.setOwnerid(aBoxSession.getID());
    }

    String FileDir = BoxStatic.HOME_DIR + BoxStatic.DOWNLOAD_FILE_DIR;
    File libDir = new File(FileDir);
    if (!libDir.exists())
    {
      if (!libDir.mkdir())
      {
        String msg = "Failed to creat the file library directory:" + FileDir;
        logger.error(msg);
        sendError(msg, req, resp);
        return;
      }
    }
    FileDir = FileDir+File.separator;
    MultipartRequest multi = new MultipartRequest(req, FileDir);

// Get the list of files to be uploaded
    Enumeration files = multi.getFileNames();

// Right now, we only support one file at a time
    String tmp = null;
    if (files.hasMoreElements() )
    {
// Get the name of the file
      String name = (String)files.nextElement();

// Get the file system name of the file
      tmp = multi.getFilesystemName(name);

// When updating, may not need to upload file again
      File f = multi.getFile(name);
      if (f != null)
      {
        entry.setSize(f.length());
        entry.setFilename(tmp);
        if (isNew & (f.length() <= 0 || tmp==null || tmp.length() <=0))
        {
          String msg = "Error upload file:" + tmp;
          logger.error(msg);
          sendError(msg, req, resp);
          return;
        }
      }
      tmp = BoxStatic.HOME_DIR + BoxStatic.DOWNLOAD_FILE_DIR+File.separator + entry.getID();
      if (f != null)
      {
        f.renameTo(new File(tmp));
        entry.setType(multi.getContentType(name));
        logger.debug("Rename file: " + entry.getFilename() + " to: " + tmp);
      }
    }

    tmp = multi.getParameter("NAME");
    if (tmp==null || tmp.length()==0)
      entry.setName(entry.getFilename());
    else
      entry.setName(tmp);
    entry.setIsfolder(false);
    entry.setLastmodifiedtime(new Timestamp(System.currentTimeMillis()));
    entry.setDescription(multi.getParameter("DESCRIPTION"));
    entry.setVersion((short)0);

    tmp = multi.getParameter("FILENAME");
    if (tmp != null && tmp.length() > 0)
      entry.setFilename(tmp);
    tmp = multi.getParameter("READONLY");
    long curAttr = entry.getAttributes();
    if ( tmp != null )
    {
      if (tmp.compareTo("1") == 0)
        curAttr |= home.READONLY;
      else
        curAttr &= ~home.READONLY;
    }
    else
      curAttr &= ~home.READONLY;

    tmp = multi.getParameter("INHERIT");
    if (tmp != null) {
      if (tmp.compareTo("1") == 0)
        curAttr |= home.INHERIT;
      else
        curAttr &= ~home.INHERIT;
    }
    else
      curAttr &= ~home.INHERIT;

    entry.setAttributes(curAttr);
    logger.debug(entry);
    home.update(entry);

    String[] permissions = multi.getParameterValues("PERMISSIONS");
    home.updatePermissions(entry, permissions);

    entry = home.get(entry.getParent());
    session.setAttribute("filelib.CURENTRY", entry);
    sendFile(folderContentJSP, req, resp);

    if (logger.isDebugEnabled())
      logger.debug("====== End of UploadFileAction ======");
  }
  public void setFolderContentJSP(String str)
  {
    folderContentJSP = str;
  }
}
